package org.ksug.samples.springmvc;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class AccountFormController extends SimpleFormController {

	private AccountRepository repository;
	private final Date today = new Date();

	public AccountFormController() {
		this.setCommandClass(Account.class);
		this.setCommandName("account");
		this.setFormView("accounts/add");
		this.setValidator(new AccountValidator());
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Account account = (Account) super.formBackingObject(request);
		account.setNumber(repository.getNextNumber());
		account.setRegistrationDate(this.today);
		return account;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map model = new HashMap();
		model.put("countries", Country.values());
		return model;
	}

	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Country.class, new CountryEditor());
	}
	
	@Override
	protected ModelAndView onSubmit(Object account) throws Exception {
		repository.add((Account) account);
		return new ModelAndView("redirect:/accounts/list.do");
	}

	public void setRepository(AccountRepository repository) {
		this.repository = repository;
	}
}
